package com.example.llh.weather_llh_21;


import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private TextView tvCity, tvTemperature, tvHumidity, tvPm25, tvTime, tvWeatherType;
    private RecyclerView rvForecast;
    private ImageView ivWeatherIcon;
    private EditText etCitySearch;
    private Button btnSearch;
    private View mainLayout;

    public String baseUrl = "http://t.weather.itboy.net/api/weather/city/";
    public String defaultCityCode = "101230101"; // 默认城市代码：福州

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setupViews();
        loadWeatherData(defaultCityCode);
    }

    private void setupViews() {
        tvCity = findViewById(R.id.tvCity);
        tvHumidity = findViewById(R.id.tvHumidity);
        tvPm25 = findViewById(R.id.tvPm25);
        tvTime = findViewById(R.id.tvTime);
        tvTemperature = findViewById(R.id.tvTemperature);
        tvWeatherType = findViewById(R.id.tvWeatherType);
        ivWeatherIcon = findViewById(R.id.ivWeatherIcon);
        etCitySearch = findViewById(R.id.etCitySearch);
        btnSearch = findViewById(R.id.btnSearch);

        // 引用主布局
        mainLayout = findViewById(R.id.main_layout);

        rvForecast = findViewById(R.id.rvForecast);
        rvForecast.setLayoutManager(new LinearLayoutManager(this));

        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 隐藏键盘
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                if (imm != null && getCurrentFocus() != null) {
                    imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                }

                String cityName = etCitySearch.getText().toString().trim();
                if (!cityName.isEmpty()) {
                    String cityCode = getCityCodeByName(cityName);
                    if (cityCode != null) {
                        loadWeatherData(cityCode);
                    } else {
                        Toast.makeText(MainActivity.this, "未找到该城市", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(MainActivity.this, "请输入城市名称", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private String getCityCodeByName(String cityName) {
        if (cityName.contains("北京")) return "101010100";
        if (cityName.contains("上海")) return "101020100";
        if (cityName.contains("广州")) return "101280101";
        if (cityName.contains("深圳")) return "101280601";
        if (cityName.contains("福州")) return "101230101";
        return null;
    }

    private void loadWeatherData(String cityCode) {
        String url = baseUrl + cityCode;
        new WeatherTask().execute(url);
    }

    private class WeatherTask extends AsyncTask<String, Void, WeatherResponse> {
        @Override
        protected WeatherResponse doInBackground(String... urls) {
            try {
                String jsonResponse = NetworkUtils.fetchWeatherData(urls[0]);
                return WeatherParser.parse(jsonResponse);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(WeatherResponse result) {
            if (result != null && result.getStatus() == 200) {
                updateWeatherUI(result);
            } else {
                Toast.makeText(MainActivity.this, "获取天气数据失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void updateWeatherUI(WeatherResponse response) {
        WeatherResponse.CityInfo cityInfo = response.getCityInfo();
        WeatherResponse.WeatherData data = response.getData();

        tvTime.setText("更新时间：" + response.getTime());
        tvCity.setText(cityInfo.getCity());
        tvHumidity.setText(data.getShidu());
        tvPm25.setText(String.valueOf(data.getPm25()));

        // 从forecast列表中获取当天的温度数据
        if (data.getForecast() != null && !data.getForecast().isEmpty()) {
            WeatherResponse.Forecast today = data.getForecast().get(0);
            // 提取当前温度
            String highTemp = today.getHigh();
            String lowTemp = today.getLow();

            // 从"高温 XX℃"和"低温 XX℃"格式中提取数字
            String currentTemp = extractTemperature(highTemp, lowTemp);
            tvTemperature.setText(currentTemp);

            // 设置天气类型
            String weatherType = today.getType();
            tvWeatherType.setText(weatherType);
            setWeatherIcon(weatherType);
            setBackgroundByWeatherType(weatherType);
        }

        rvForecast.setAdapter(new ForecastAdapter(data.getForecast()));
    }

    // 从"高温 XX℃"和"低温 XX℃"格式中提取温度数值
    private String extractTemperature(String highTemp, String lowTemp) {
        try {
            // 从字符串中提取数字部分
            int high = Integer.parseInt(highTemp.replaceAll("[^0-9]", ""));
            int low = Integer.parseInt(lowTemp.replaceAll("[^0-9]", ""));

            // 计算平均温度
            int avgTemp = (high + low) / 2;
            return avgTemp + "℃";
        } catch (Exception e) {
            e.printStackTrace();
            return "N/A";
        }
    }

    private void setWeatherIcon(String weatherType) {
        if (weatherType.contains("晴")) {
            ivWeatherIcon.setImageResource(R.drawable.ic_sunny);
        } else if (weatherType.contains("雨")) {
            ivWeatherIcon.setImageResource(R.drawable.ic_rainy);
        } else if (weatherType.contains("雪")) {
            ivWeatherIcon.setImageResource(R.drawable.ic_snowy);
        } else {
            ivWeatherIcon.setImageResource(R.drawable.ic_cloudy);
        }
    }

    private void setBackgroundByWeatherType(String weatherType) {
        if (weatherType.contains("晴")) {
            mainLayout.setBackgroundColor(getResources().getColor(R.color.weather_background_clear));
        } else if (weatherType.contains("雨")) {
            mainLayout.setBackgroundColor(getResources().getColor(R.color.weather_background_rainy));
        } else if (weatherType.contains("雪")) {
            mainLayout.setBackgroundColor(getResources().getColor(R.color.weather_background_snowy));
        } else {
            mainLayout.setBackgroundColor(getResources().getColor(R.color.weather_background_cloudy));
        }
    }
}